<template>
    <div class="dormitory-list">
        <el-card shadow="hover">
            <template #header>
                <div class="card-header">
                    <span class="title">宿舍列表</span>
                    <div class="header-actions">
                        <el-button type="success" @click="handleDownloadTemplate">
                            <el-icon>
                                <Download />
                            </el-icon>
                            下载模板
                        </el-button>
                        <el-upload
                            ref="uploadRef"
                            :action="uploadAction"
                            :headers="uploadHeaders"
                            :show-file-list="false"
                            :before-upload="beforeUpload"
                            :on-success="handleUploadSuccess"
                            :on-error="handleUploadError"
                            :on-progress="handleUploadProgress"
                            accept=".xlsx,.xls"
                        >
                            <el-button type="warning">
                                <el-icon>
                                    <Upload />
                                </el-icon>
                                导入Excel
                            </el-button>
                        </el-upload>
                        <el-button type="info" @click="handleExport">
                            <el-icon>
                                <Download />
                            </el-icon>
                            导出数据
                        </el-button>
                        <el-button 
                            type="danger" 
                            plain 
                            @click="handleBatchDelete" 
                            :disabled="selectedRows.length === 0"
                        >
                            <el-icon>
                                <Delete />
                            </el-icon>
                            批量删除 ({{ selectedRows.length }})
                        </el-button>
                        <el-button type="primary" @click="handleAdd">
                            <el-icon>
                                <Plus />
                            </el-icon>
                            添加宿舍
                        </el-button>
                    </div>
                </div>
            </template>

            <!-- 搜索区域 -->
            <el-form :inline="true" :model="searchForm" class="search-form">
                <el-form-item label="楼栋">
                    <el-select v-model="searchForm.building" style="width: 200px" clearable filterable>
                        <el-option label="全部" value="" />
                        <el-option 
                            v-for="building in buildingList" 
                            :key="building.buildingName" 
                            :label="building.buildingName" 
                            :value="building.buildingName" 
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="宿舍号">
                    <el-input v-model="searchForm.roomNumber" placeholder="请输入宿舍号" clearable />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">
                        <el-icon>
                            <Search />
                        </el-icon>
                        查询
                    </el-button>
                    <el-button @click="handleReset">
                        <el-icon>
                            <Refresh />
                        </el-icon>
                        重置
                    </el-button>
                </el-form-item>
            </el-form>

            <!-- 表格 -->
            <el-table 
                :data="tableData" 
                style="width: 100%" 
                v-loading="loading" 
                border 
                max-height="calc(100vh - 350px)"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" />
                <el-table-column prop="building" label="楼栋" width="150" />
                <el-table-column prop="roomNumber" label="宿舍号" width="150" />
                <el-table-column prop="floor" label="楼层" width="150" />
                <el-table-column prop="capacity" label="容纳人数" width="150" />
                <el-table-column prop="occupied" label="已入住" width="150" />
                <el-table-column prop="available" label="空余床位" width="150" />
                <el-table-column label="使用率" width="150">
                    <template #default="scope">
                        <el-progress :percentage="Math.round((scope.row.occupied / scope.row.capacity) * 100)"
                            :color="getProgressColor(scope.row.occupied, scope.row.capacity)" />
                    </template>
                </el-table-column>
                <el-table-column label="状态" width="150">
                    <template #default="scope">
                        <el-tag :type="getStatusType(scope.row.status)">
                            {{ scope.row.status }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="remark" label="备注" show-overflow-tooltip width="400"/>
                <el-table-column label="操作" width="200" fixed="right">
                    <template #default="scope">
                        <el-button type="primary" text @click="handleEdit(scope.row)">
                            <el-icon>
                                <Edit />
                            </el-icon>
                            编辑
                        </el-button>
                        <el-button type="danger" text @click="handleDelete(scope.row)">
                            <el-icon>
                                <Delete />
                            </el-icon>
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]" :total="total" layout="total, sizes, prev, pager, next, jumper"
                class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </el-card>

        <!-- 添加/编辑宿舍弹窗 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="700px" :close-on-click-modal="false"
            @close="handleDialogClose">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" class="dormitory-form">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="楼栋" prop="building">
                            <el-select 
                                v-model="form.building" 
                                placeholder="请选择楼栋" 
                                style="width: 100%"
                                :disabled="isEdit"
                                filterable
                            >
                                <el-option 
                                    v-for="building in buildingList" 
                                    :key="building.buildingName" 
                                    :label="building.buildingName" 
                                    :value="building.buildingName" 
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="宿舍号" prop="roomNumber">
                            <el-input v-model="form.roomNumber" placeholder="请输入宿舍号" :disabled="isEdit" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="楼层" prop="floor">
                            <el-input-number v-model="form.floor" :min="1" :max="20" style="width: 100%" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="容纳人数" prop="capacity">
                            <el-input-number v-model="form.capacity" :min="1" :max="8" style="width: 100%"
                                @change="handleCapacityChange" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="已入住" prop="occupied">
                            <el-input-number v-model="form.occupied" :min="0" :max="form.capacity" style="width: 100%"
                                @change="handleOccupiedChange" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="空余床位">
                            <el-input :model-value="form.available" disabled style="width: 100%" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="状态" prop="status">
                    <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
                        <el-option label="可用" value="可用" />
                        <el-option label="满员" value="满员" />
                        <el-option label="维修中" value="维修中" />
                        <el-option label="待分配" value="待分配" />
                    </el-select>
                </el-form-item>

                <el-form-item label="备注">
                    <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 上传进度对话框 -->
        <el-dialog v-model="uploadVisible" title="导入宿舍数据" width="400px" :close-on-click-modal="false" :show-close="false">
            <div style="text-align: center; padding: 20px;">
                <el-progress :percentage="uploadProgress" :stroke-width="15" />
                <p style="margin-top: 20px; color: #666;">正在上传文件，请稍候...</p>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Edit, Delete, Download, Upload } from '@element-plus/icons-vue'
import {
    getDormitoryList,
    addDormitory,
    updateDormitory,
    deleteDormitory,
    batchDeleteDormitories,
    downloadDormitoryTemplate,
    exportDormitories
} from '@/api/dormitory'
import { getBuildingList } from '@/api/building'
import { useAuthStore } from '@/stores/auth'

const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const searchForm = ref({
    building: '',
    roomNumber: ''
})

// 楼栋列表
const buildingList = ref([])

const tableData = ref([])
const selectedRows = ref([])

// 上传相关
const authStore = useAuthStore()
const uploadRef = ref(null)
const uploadAction = computed(() => {
    const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:9001/api'
    return `${baseURL}/dormitory/import`
})
const uploadHeaders = computed(() => ({
    'Authorization': `Bearer ${authStore.token}`,
    'token': authStore.token
}))
const uploadVisible = ref(false)
const uploadProgress = ref(0)

// 弹窗相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const submitLoading = ref(false)
const formRef = ref(null)
const currentEditIndex = ref(-1)

const dialogTitle = computed(() => {
    return isEdit.value ? '编辑宿舍' : '添加宿舍'
})

const form = ref({
    building: '',
    roomNumber: '',
    floor: 1,
    capacity: 4,
    occupied: 0,
    available: 4,
    status: '可用',
    remark: ''
})

const rules = {
    building: [
        { required: true, message: '请选择楼栋', trigger: 'change' }
    ],
    roomNumber: [
        { required: true, message: '请输入宿舍号', trigger: 'blur' }
    ],
    floor: [
        { required: true, message: '请输入楼层', trigger: 'blur' }
    ],
    capacity: [
        { required: true, message: '请输入容纳人数', trigger: 'blur' }
    ]
}

// 重置表单
const resetForm = () => {
    form.value = {
        building: '',
        roomNumber: '',
        floor: 1,
        capacity: 4,
        occupied: 0,
        available: 4,
        status: '可用',
        remark: ''
    }
}

// 计算空余床位
const calculateAvailable = () => {
    form.value.available = form.value.capacity - form.value.occupied
}

// 容纳人数改变
const handleCapacityChange = () => {
    if (form.value.occupied > form.value.capacity) {
        form.value.occupied = form.value.capacity
    }
    calculateAvailable()
}

// 已入住人数改变
const handleOccupiedChange = () => {
    calculateAvailable()
}

// 获取宿舍列表
const fetchDormitoryList = async () => {
    loading.value = true
    try {
        const params = {
            page: currentPage.value,
            pageSize: pageSize.value,
            ...searchForm.value
        }
        const res = await getDormitoryList(params)
        if (res.code === 200 || res.code === 0) {
            tableData.value = res.data.list || res.data
            total.value = res.data.total || 0
        }
    } catch (error) {
        console.error('获取宿舍列表失败:', error)
        tableData.value = [
            { id: 1, building: 'A栋', roomNumber: '101', floor: 1, capacity: 4, occupied: 4, available: 0, status: '满员', remark: '标准四人间' },
            { id: 2, building: 'A栋', roomNumber: '102', floor: 1, capacity: 4, occupied: 3, available: 1, status: '可用', remark: '标准四人间' }
        ]
        total.value = tableData.value.length
    } finally {
        loading.value = false
    }
}

// 添加宿舍
const handleAdd = () => {
    resetForm()
    isEdit.value = false
    dialogVisible.value = true
}

// 编辑宿舍
const handleEdit = (row) => {
    isEdit.value = true
    currentEditIndex.value = row.id
    form.value = { ...row }
    dialogVisible.value = true
}

// 表格选择变化
const handleSelectionChange = (selection) => {
    selectedRows.value = selection
}

// 批量删除宿舍
const handleBatchDelete = async () => {
    try {
        await ElMessageBox.confirm(
            `确定要删除选中的 ${selectedRows.value.length} 个宿舍吗？删除后将无法恢复！`,
            '批量删除确认',
            {
                confirmButtonText: '确定删除',
                cancelButtonText: '取消',
                type: 'warning',
                distinguishCancelAndClose: true
            }
        )

        const ids = selectedRows.value.map(row => row.id)
        const res = await batchDeleteDormitories(ids)

        if (res.code === 200 || res.code === 0) {
            ElMessage.success(res.message || `批量删除成功，共删除 ${ids.length} 条数据`)
            selectedRows.value = []
            fetchDormitoryList()
        } else {
            ElMessage.error(res.message || '批量删除失败')
        }
    } catch (error) {
        if (error !== 'cancel' && error !== 'close') {
            console.error('批量删除宿舍失败:', error)
            ElMessage.error(error.message || '批量删除失败')
        }
    }
}

// 删除宿舍
const handleDelete = async (row) => {
    try {
        await ElMessageBox.confirm(`确定要删除宿舍 ${row.building} ${row.roomNumber} 吗？`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        const res = await deleteDormitory(row.id)
        if (res.code === 200 || res.code === 0) {
            ElMessage.success('删除成功')
            fetchDormitoryList()
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除宿舍失败:', error)
        }
    }
}

// 提交表单
const handleSubmit = async () => {
    formRef.value.validate(async (valid) => {
        if (valid) {
            submitLoading.value = true
            try {
                if (isEdit.value) {
                    const res = await updateDormitory(currentEditIndex.value, form.value)
                    if (res.code === 200 || res.code === 0) {
                        ElMessage.success('修改成功')
                        dialogVisible.value = false
                        fetchDormitoryList()
                    }
                } else {
                    const res = await addDormitory(form.value)
                    if (res.code === 200 || res.code === 0) {
                        ElMessage.success('添加成功')
                        dialogVisible.value = false
                        fetchDormitoryList()
                    }
                }
            } catch (error) {
                console.error('提交失败:', error)
            } finally {
                submitLoading.value = false
            }
        }
    })
}

// 弹窗关闭时重置表单
const handleDialogClose = () => {
    formRef.value?.resetFields()
    resetForm()
    currentEditIndex.value = -1
}

// 下载模板
const handleDownloadTemplate = async () => {
    try {
        await downloadDormitoryTemplate()
        ElMessage.success('模板下载成功')
    } catch (error) {
        console.error('下载模板失败:', error)
        ElMessage.error('下载模板失败')
    }
}

// 导出数据
const handleExport = async () => {
    try {
        await exportDormitories()
        ElMessage.success('导出成功')
    } catch (error) {
        console.error('导出失败:', error)
        ElMessage.error('导出失败')
    }
}

// 上传前校验
const beforeUpload = (file) => {
    const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                   file.type === 'application/vnd.ms-excel'
    const isLt10M = file.size / 1024 / 1024 < 10

    if (!isExcel) {
        ElMessage.error('只能上传 Excel 文件！')
        return false
    }
    if (!isLt10M) {
        ElMessage.error('文件大小不能超过 10MB！')
        return false
    }

    uploadVisible.value = true
    uploadProgress.value = 0
    return true
}

// 上传进度
const handleUploadProgress = (event) => {
    uploadProgress.value = Math.floor((event.loaded / event.total) * 100)
}

// 上传成功
const handleUploadSuccess = (response) => {
    uploadVisible.value = false
    uploadProgress.value = 0

    if (response.code === 200 || response.code === 0) {
        ElMessage.success(response.message || '导入成功')
        fetchDormitoryList()
    } else {
        ElMessage.error(response.message || '导入失败')
    }
}

// 上传失败
const handleUploadError = (error) => {
    uploadVisible.value = false
    uploadProgress.value = 0
    console.error('上传失败:', error)
    ElMessage.error('上传失败，请重试')
}

// 搜索
const handleSearch = () => {
    currentPage.value = 1
    fetchDormitoryList()
}

// 重置搜索
const handleReset = () => {
    searchForm.value = {
        building: '',
        roomNumber: ''
    }
    handleSearch()
}

// 获取楼栋列表
const fetchBuildingList = async () => {
    try {
        const res = await getBuildingList({ page: 1, pageSize: 100 })
        if (res.code === 200 || res.code === 0) {
            buildingList.value = res.data.list || res.data || []
        }
    } catch (error) {
        console.error('获取楼栋列表失败:', error)
        // 使用模拟数据
        buildingList.value = [
            { buildingName: 'A栋' },
            { buildingName: 'B栋' },
            { buildingName: 'C栋' },
            { buildingName: 'D栋' }
        ]
    }
}

// 分页
const handleSizeChange = (val) => {
    pageSize.value = val
    currentPage.value = 1
    fetchDormitoryList()
}

const handleCurrentChange = (val) => {
    currentPage.value = val
    fetchDormitoryList()
}

// 初始化
onMounted(() => {
    fetchBuildingList()
    fetchDormitoryList()
})

// 进度条颜色
const getProgressColor = (occupied, capacity) => {
    const rate = occupied / capacity
    if (rate >= 0.9) return '#f56c6c'
    if (rate >= 0.6) return '#e6a23c'
    return '#67c23a'
}

// 状态类型
const getStatusType = (status) => {
    const typeMap = {
        '可用': 'success',
        '满员': 'danger',
        '维修中': 'warning',
        '待分配': 'info'
    }
    return typeMap[status] || 'info'
}
</script>

<style lang="scss" scoped>
.dormitory-list {
    .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .title {
            font-size: 18px;
            font-weight: 600;
            color: #333;
        }

        .header-actions {
            display: flex;
            gap: 10px;
            align-items: center;
        }
    }

    .search-form {
        margin-bottom: 20px;
    }

    .pagination {
        margin-top: 20px;
        display: flex;
        justify-content: flex-end;
    }

    .dormitory-form {
        padding: 20px 20px 0;

        :deep(.el-input-number) {
            width: 100%;
        }
    }

    .dialog-footer {
        display: flex;
        justify-content: flex-end;
        gap: 10px;
    }
}
</style>
